package com.character.aop;

import com.character.entity.Log;
import com.character.entity.User;
import com.character.service.LogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * @ fileName:LogAspect
 * @ description:
 * @ author:ftw
 * @ createTime:2021/12/8 9:51
 * @ version:1.0.0
 */
@EnableAspectJAutoProxy
@Component
@Aspect
public class LogAspect {
    @Autowired
    private LogService logService;

    //切入点表达式，切入到所有的controller中的方法
    @Pointcut("execution(* com.character.controller.*.*(..))&&"+"!execution(* com.character.controller.ResultController.*(..))")
    public void p() {
    }

    @Around("p()")
    public Object myEnhance(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        Log log = new Log();
        //获取登录名,用户名
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        User user = new User();
        if (principal != null) {
            user = (User) principal;
        }
        //传入固定数据
//        User user =new User();
//        user.setLoginName("gjl");
//        user.setUserName("高杰领");
        log.setLoginName(user.getLoginName());
        log.setUserName(user.getUserName());

        //获取请求方的ip地址
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String remoteAddr = request.getRemoteAddr();
        log.setIp(remoteAddr);

        //获取类名
        String className = joinPoint.getTarget().getClass().getName();
        log.setClassName(className);
        //获取方法名
        String[] split = signature.toString().split("\\.");
        String methodName = split[split.length - 1];
        log.setMethodName(methodName);
        //获取参数
        String paramString = Arrays.toString(args);
        log.setParams(paramString);
        //设置时间
        log.setOperationTime(new Date());
        logService.save(log);
        try {
            Object proceed = joinPoint.proceed(args);
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
